<!-- 富文本编辑器 -->
<template>
  <div class="tinymce-editor">
    <editor v-model="myValue" :init="init" :disabled="disabled" @onClick="onClick" style="height: 100%; width: 100%">
    </editor>
  </div>
</template>

<script>
import tinymce from 'tinymce/tinymce'
import Editor from '@tinymce/tinymce-vue'
import 'tinymce/themes/silver/theme'
import 'tinymce/plugins/image' // 插入上传图片插件
import 'tinymce/plugins/link' // 超链接插件
import 'tinymce/plugins/code' // 代码块插件
import 'tinymce/plugins/table' // 插入表格插件
import 'tinymce/plugins/lists' // 列表插件
import 'tinymce/plugins/contextmenu' // 右键菜单插件
import 'tinymce/plugins/wordcount' // 字数统计插件
import 'tinymce/plugins/colorpicker' // 选择颜色插件
import 'tinymce/plugins/textcolor' // 文本颜色插件
import 'tinymce/plugins/fullscreen' // 全屏
import 'tinymce/plugins/paste'
export default {
    name: 'tinymceeditor',
    components: {
        Editor
    },
    props: {
        value: {
            type: String,
            required: false
        },
        disabled: {
            type: Boolean,
            default: false
        },
        plugins: {
            type: [String, Array],
            default: 'link image  table lists fullscreen'
        },
        toolbar: {
            type: [String, Array],
            default:
        'undo redo | fullscreen | formatselect alignleft aligncenter alignright alignjustify | link unlink | numlist bullist | image media table | fontselect fontsizeselect forecolor backcolor | bold italic underline strikethrough | indent outdent | superscript subscript | removeformat |',
            branding: false
        }
    },
    data() {
        return {
            init: {
                elementpath: false, // 隐藏元素路径，不明白的可以切换true/false观察页面
                statusbar: false,
                resize: false,
                height: 200, // 初始化富文本编辑器的高度
                branding: false,
                menubar: false,
                toolbar: this.toolbar,
                toolbar_drawer: 'sliding',
                quickbars_selection_toolbar:
          'removeformat | bold italic underline strikethrough | fontsizeselect forecolor backcolor',
                plugins: this.plugins,
                language: 'zh_CN',
                init_instance_callback: editor => {
                    if (this.content) {
                        editor.setContent(this.content)
                    }
                    this.finishInit = true
                    editor.on('NodeChange Change SetContent KeyUp', () => {
                        this.hasChanged = true
                    })
                }, // 上传图片
                convert_urls: false,
                automatic_uploads: true, // 开启点击图片上传时，自动进行远程上传操作
                images_upload_base_path: `${process.env.VUE_APP_GOLDWIND_BASE_API}`, // 图片上传的基本路径
                images_upload_url: '/v2/file/upload',
                images_upload_handler: (blobInfo, success, failure) => {
                    var xhr, formData

                    xhr = new XMLHttpRequest()
                    xhr.withCredentials = false
                    xhr.open('POST', `${process.env.VUE_APP_GOLDWIND_BASE_API}` + '/v2/file/upload')
                    xhr.setRequestHeader('token', JSON.parse(sessionStorage.getItem('USERINFO')).token)
                    // xhr.setRequestHeader('token', JSON.parse(sessionStorage.getItem('USERINFO')).token);

                    formData = new FormData()
                    formData.append('file', blobInfo.blob())

                    formData.append('checkOfficeFmt', false)
                    formData.append('isTmp', false)
                    xhr.onload = function(e) {
                        var json
                        console.log(e, xhr)
                        console.log(this)

                        if (xhr.errcode == '0') {
                            failure('服务器错误:' + xhr.msg)
                            return
                        }
                        json = JSON.parse(this.responseText)
                        if (!json.data || typeof json.data.fileSourceId != 'string') {
                            failure('服务器错误')
                            return
                        }
                        success(
                            `${process.env.VUE_APP_GOLDWIND_BASE_API}` +
                '/v2/file/download?' +
                '&fileSourceId=' +
                json.data.fileSourceId
                        )
                    }
                    xhr.send(formData)
                },
                image_advtab: false,
                language_url: 'tinymce/langs/zh_CN.js' // 语言包的路径
            },
            myValue: this.value
        }
    },
    mounted() {
        tinymce.init({})
    },
    methods: {
        onClick(e) {
            this.$emit('onClick', e, tinymce)
        },
        // 可以添加一些自己的自定义事件，如清空内容
        clear() {
            this.myValue = ''
        },
        upload(blobInfo, success, failure) {
            var xhr, formData

            xhr = new XMLHttpRequest()
            xhr.withCredentials = false
            xhr.open('POST', `${process.env.VUE_APP_GOLDWIND_BASE_API}` + '/v2/file/upload')
            xhr.setRequestHeader('token', JSON.parse(sessionStorage.getItem('USERINFO')).token)
            // xhr.setRequestHeader('token', JSON.parse(sessionStorage.getItem('USERINFO')).token);

            formData = new FormData()
            formData.append('file', blobInfo.blob())

            formData.append('checkOfficeFmt', false)
            formData.append('isTmp', false)
            xhr.onload = function(e) {
                var json
                console.log(e, xhr)
                console.log(this)

                if (xhr.errcode == '0') {
                    failure('服务器错误:' + xhr.msg)
                    return
                }
                json = JSON.parse(this.responseText)
                if (!json.data || typeof json.data.fileSourceId != 'string') {
                    failure('服务器错误')
                    return
                }
                success(
                    `${process.env.VUE_APP_GOLDWIND_BASE_API}` + '/v2/file/download?' + '&fileSourceId=' + json.data.fileSourceId
                )
            }
            xhr.send(formData)
        }
    },
    watch: {
        value(newValue) {
            this.myValue = newValue == null ? '' : newValue
        },
        myValue(newValue) {
            if (this.triggerChange) {
                this.$emit('change', newValue)
            } else {
                this.$emit('input', newValue)
            }
        }
    }
}
</script>

<style scoped>
.tinymce-editor {
  width: 100%;
  height: 100%;
}
</style>
